// pages/ordersPath/ordersPath.js

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // colorDone: [235, 110, 110],
    colorNotDone: [235, 110, 110],
    ordersNeedToDone: [],
    ordersNeedToSend: [],
    ordersAll: [],
    selectUrl: "/portal/orders/person/",
    cancelUrl: "/portal/orders/cancel/user",
  },

  finish(e) {
    console.log("完成订单：" + e.currentTarget.dataset.item.id)
  },

  setNumb(e) {
    console.log(e.currentTarget.dataset.step),
    this.setNumbA(e.currentTarget.dataset.step)
  },

  toComment(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/comment/comment',
      success: function(res) {
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: id })
      }
    })
  },

  cancelOrder(e) {
    Dialog.confirm({
      message: '确认取消订单',
    })
      .then(() => {
        // on confirm
        console.log(e.currentTarget.dataset.id);
        wx.request({
          url: this.data.cancelUrl,
          method: "POST",
          data: {
            userId: this.getUser().id,
            orderId: e.currentTarget.dataset.id,
          },
          success: (res) => {
            this.getOrders();
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 挂载全局数据
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['user'],
      actions: ['getUser', 'getWebsite']
    });

    this.setData({
      selectUrl: this.getWebsite() + this.data.selectUrl,
      cancelUrl: this.getWebsite() + this.data.cancelUrl,
    });
    // this.getOrders();
  },

  getOrders() {
    // 展示loading
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });

    // 根据用户id更新追踪订单的网址
    let url = this.data.selectUrl + this.getUser().id;
    wx.request({
      url: url,
      method: "GET",
      success: (result) => {
        if (result.data.code == 20004) {
          console.log(result.data.data);
          //对期日格式化
          for (let index = 0; index < result.data.data.length; index++) {
            if (result.data.data[index].orderAcceptTime != null) {
              result.data.data[index].orderAcceptTime = this.formatDate(result.data.data[index].orderAcceptTime);
            }
            if (result.data.data[index].orderFinishTime != null) {
              result.data.data[index].orderFinishTime = this.formatDate(result.data.data[index].orderFinishTime);
            }
          }
          this.setData({
            ordersAll: result.data.data
          });
          // 分割待完成的订单
          let needToDone = [];
          for (let index = 0; index < this.data.ordersAll.length; index++) {
            const element = this.data.ordersAll[index];
            if (element.orderFinishTime == null) {
              needToDone.push(element);
            }
          }
          this.setData({
            ordersNeedToDone: needToDone
          });
          // 分割待配送订单
          let needToSend = [];
          for (let index = 0; index < this.data.ordersAll.length; index++) {
            const element = this.data.ordersAll[index];
            if (element.orderFinishTime == null && element.orderAcceptTime != null) {
              needToDone.push(element);
            }
          }
          this.setData({
            ordersNeedToSend: needToSend
          });
        }
      },
      complete() {
        Toast.clear();
      }
    })
  },

  formatDate (time) {
    var date = new Date(time);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = function () { //获取小时
        return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    }
    var minute = function () { //获取分钟
        return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    }

    var second = function () { //获取秒数
        return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    }
    return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOrders();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 销毁挂载绑定
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})